<?php

namespace Icsoc\CoreBundle\Common;

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 公共方法
 * Class Common
 * @package Icsoc\CoreBundle\Common
 */
class Common
{

    /** @var array 特殊菜单；需要判断配置是否启用 */
    private $specialMenu = array(
        '40'=>'getIsEnableWhite',
        '38'=>array('getIsEnableBlack', 'getIsIncomingEnableBlack'),
        '51'=>'getIsEnableGroup',
    );

    /** @var array 键值；好判断 */
    private $keys = array(40, 38, 51);

    /** @var  ContainerInterface */
    private $container;

    /** @var array 特殊的角色id */
    private $roles = array(516);

    /**
     * Common constructor.
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param string $str
     * @return string
     */
    public function sbc2Dbc($str)
    {
        $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
            '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
            'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
            'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
            'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
            'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
            'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
            'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
            'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
            'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
            'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
            'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
            'ｙ' => 'y', 'ｚ' => 'z',
            '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
            '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
            '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<', '》' => '>',
            '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
            '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
            '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
            '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
            '　' => ' ',
            );

        return strtr($str, $arr);
    }

    /**
     * 获取查看的权限
     * @return array
     */
    public function getUserTypeCondition()
    {
        $data = array();
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $userFlag = $user->getFlag();
        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $userType = (string) $user->getUserType();
        $userId = $user->getUserId();
        $vccId = $user->getVccId();
        $cacheKey = "user.condition.".$vccId.".".$userId.".".$userType;
        $cachedata = $this->container->get("icsoc_core.common.class")->getCache($cacheKey);
        if (empty($cachedata)) {
            switch ($userType) {
                case '':
                    break;
                case '0':
                    //不限，查询下属角色
                    if ($userFlag == 'ccadmin') {
                        break;
                    }
                    $vccId = $user->getVccId();
                    $roles = $em->getRepository("IcsocSecurityBundle:CcRoles")
                        ->getRolesName("r.vccId = :vccId AND r.roleGrade > 1", array('vccId'=>$vccId));
                    $roleIds = array_keys($roles);
                    $data['user_role'] = $roleIds;
                    break;
                case '1':
                    //按技能组
                    $userQueues = $user->getUserQueues();
                    $uq = explode(",", $userQueues);
                    //-1为管理自己所属的技能组；
                    if (in_array(-1, $uq) && $userFlag == 'agent') {
                        $agenId = $user->getId();
                        $queues = $em->getRepository("IcsocSecurityBundle:WinAgqu")->getQueId($agenId);
                        $uq = array_unique(array_merge($uq, array_column($queues, 'queId')));
                    }
                    $ags = $em->getRepository("IcsocSecurityBundle:WinAgqu")->getAgId($uq);
                    $agqu = array(0);
                    foreach ($ags as $k => $v) {
                        $agqu[$k] = $v['agId'];
                    }
                    $data['ag_id'] = $agqu;
                    /** 报表数据权限 */
                    $data['que_id'] = $uq;
                    /** 各个报表获取技能组所需要的数据 */
                    $data['get_que_ids'] = $uq;
                    break;
                case '2':
                    //坐席
                    $data['ag_id'] = array($user->getUserId());
                    $data['que_id'] = array();
                    /** 各个报表获取技能组所需要的数据 */
                    //$userQueues = $user->getUserQueues();
                    //$uq = explode(",", $userQueues);
                    $uqs = $em->getRepository("IcsocSecurityBundle:WinAgqu")->getQueId($user->getUserId());
                    $uq = array();
                    foreach ($uqs as $v) {
                        $uq[] = $v['queId'];
                    }
                    $data['get_que_ids'] = $uq;
                    break;
                case '3':
                    //按业务组
                    $vccId = $user->getVccId();
                    $userQueues = $user->getUserQueues();
                    /** 如果userQueues为空，则赋值一个不存在的id，防止下面查询的sql报错*/
                    if (empty($userQueues)) {
                        $userQueues = -1;
                    }
                    $uq = explode(",", $userQueues);
                    $conn = $this->container->get('doctrine.dbal.default_connection');
                    $ags = $conn->fetchAll("SELECT id FROM win_agent WHERE vcc_id=$vccId AND group_id IN ($userQueues)");
                    $aggr = array(0);
                    foreach ($ags as $k => $v) {
                        $aggr[$k] = $v['id'];
                    }
                    $data['ag_id'] = $aggr;
                    /** 报表数据权限 */
                    $data['group_id'] = $uq;
                    break;
            }

            $this->container->get("icsoc_core.common.class")->setCache($cacheKey, json_encode($data), 120);
        } else {
            $data = $cachedata;
        }

        return $data;
    }

    /**
     * 报表数据权限
     *
     * @param string $agId  数据库中存储坐席ID的字段
     * @param string $queId 数据库中存储技能组ID的字段
     * @param int    $type  查询字符串中返回的信息：0，返回全部包含及技能组和坐席"AND que_id IN(1,2) AND ag_id IN (1,2)" 1，
     *                      返回技能组只返回技能组"AND que_id IN(1,2)" 2，返回坐席只返回坐席"AND ag_id IN (1,2)"
     * @return string
     */
    public function getAuthorityCondition($agId, $queId, $type = 0)
    {
        $condition = '';
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $userType = $user->getUserType();
        switch ($userType) {
            /** 不限 */
            case '':
            case 0:
                break;
            /** 技能组权限 */
            case 1:
                $userQueues = $user->getUserQueues();
                if (empty($userQueues)) {
                    $condition = false;
                    break;
                }
                $queue = explode(",", $userQueues);
                if (in_array(-1, $queue)) {
                    $agenId = $user->getUserId();
                    $queues = $em->getRepository("IcsocSecurityBundle:WinAgqu")->getQueId($agenId);
                    $queue = array_unique(array_merge($queue, array_column($queues, 'queId')));
                }
                if ($type == 1 || $type == 0) {
                    $condition .= ' AND '.$queId.' IN ('.implode(',', $queue).')';
                }

                if ($type == 2 || $type == 0) {
                    $ags = $em->getRepository("IcsocSecurityBundle:WinAgqu")->getAgId($queue);
                    $agqu = array();
                    foreach ($ags as $k => $v) {
                        $agqu[$k] = $v['agId'];
                    }

                    if (empty($agqu)) {
                        $condition = false;
                        break;
                    }

                    $condition .= ' AND '.$agId.' IN ('.implode(',', $agqu).')';
                }
                break;
            /** 坐席权限 */
            case 2:
                if (empty($agId)) {
                    $condition = false;
                } else {
                    $condition .= ' AND '.$agId.' = '.$user->getUserId();
                }
                break;
            /** 业务组权限 */
            case 3:
                $vccId = $user->getVccId();
                $userQueues = $user->getUserQueues();
                if (empty($userQueues)) {
                    $condition = false;
                    break;
                }

                if ($type == 1 || $type == 0) {
                    $condition .= ' AND group_id IN ('.$userQueues.')';
                }

                if ($type == 2 || $type == 0) {
                    $conn = $this->container->get('doctrine.dbal.default_connection');
                    $ags = $conn->fetchAll("SELECT id FROM win_agent WHERE vcc_id=$vccId AND group_id IN ($userQueues)");
                    $aggr = array();
                    foreach ($ags as $k => $v) {
                        $aggr[$k] = $v['id'];
                    }

                    if (empty($aggr)) {
                        $condition = false;
                        break;
                    }

                    $condition .= ' AND '.$agId.' IN ('.implode(',', $aggr).')';
                }
                break;
        }

        return $condition;
    }

    /**
     * 报表数据权限(elasticsearch使用)
     * @param $agId
     * @param $queId
     * @param int $type
     * @return array|bool  array('ag_id' => '1,2', 'que_id' => '1,2,3')
     */
    public function getAuthorityConditionForElasearch($agId, $queId, $type = 0)
    {
        $condition = array();
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $userType = $user->getUserType();
        switch ($userType) {
            /** 不限 */
            case '':
            case 0:
                break;
            /** 技能组权限 */
            case 1:
                $userQueues = $user->getUserQueues();
                if (empty($userQueues)) {
                    $condition = false;
                    break;
                }
                $queue = explode(",", $userQueues);
                //-1为所属技能组
                if (in_array(-1, $queue)) {
                    $agenId = $user->getUserId();
                    $queues = $em->getRepository("IcsocSecurityBundle:WinAgqu")->getQueId($agenId);
                    $queue = array_values(array_unique(array_merge($queue, array_column($queues, 'queId'))));
                }
                if ($type == 1 || $type == 0) {
                    $condition[$queId] = $queue;
                }

                if ($type == 2 || $type == 0) {
                    $ags = $em->getRepository("IcsocSecurityBundle:WinAgqu")->getAgId($queue);
                    $agqu = array();
                    foreach ($ags as $k => $v) {
                        $agqu[] = $v['agId'];
                    }

                    if (empty($agqu)) {
                        $condition = false;
                        break;
                    }

                    $condition[$agId]= $agqu;
                }
                break;
            /** 坐席权限 */
            case 2:
                if (empty($agId)) {
                    $condition = false;
                } else {
                    $condition[$agId]= array($user->getUserId());
                }
                break;
            /** 业务组权限 */
            case 3:
                $vccId = $user->getVccId();
                $userQueues = $user->getUserQueues();
                if (empty($userQueues)) {
                    $condition = false;
                    break;
                }

                if ($type == 1 || $type == 0) {
                    $condition['group_id']= explode(",", $userQueues);
                }

                if ($type == 2 || $type == 0) {
                    $conn = $this->container->get('doctrine.dbal.default_connection');
                    $ags = $conn->fetchAll("SELECT id FROM win_agent WHERE vcc_id=$vccId AND group_id IN ($userQueues)");
                    $aggr = array();
                    foreach ($ags as $k => $v) {
                        $aggr[] = $v['id'];
                    }

                    if (empty($aggr)) {
                        $condition = false;
                        break;
                    }

                    $condition[$agId]= $aggr;
                }
                break;
        }

        return $condition;
    }

    /**
     * 根据roleGrade决定显示哪些后台数据权限；
     * @param array $role
     * @param int   $level
     * @return array
     */
    public function getUserTypes($role, $level)
    {
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $vccId = $user->getVccId();
        $isEnableGroup = $this->container->get('doctrine')->getRepository("IcsocSecurityBundle:CcCcodConfigs")->isEnableGroup($vccId);
        $userType = array();
        if ($level < 1) {
            $userType[0] = $role[0];
        }
        if ($level < 2) {
            $userType[1] = $role[1];
            if ($isEnableGroup) {
                $userType[3] = $role[3];
            }
        }
        if ($level < 3) {
            $userType[2] = $role[2];
        }

        return $userType;
    }

    /**
     * 根据角色等级获取前台数据权限选项
     * @param integer $roleGrade
     * @param string  $flag      1，坐席添加
     * @return mixed
     */
    public function getFrontAgentRole($roleGrade, $flag = '')
    {
        $arr = $this->container->getParameter('front_agent_type');
        switch($roleGrade){
            case 0:
                break;
            case 1:
                unset($arr[-1]);
                break;
            case 2:
                unset($arr[-1]);
                unset($arr[1]);
                break;
            default:
                if ($flag) {
                    $arr = array();
                } else {
                    unset($arr[-1]);
                    unset($arr[1]);
                }
                break;
        }

        return $arr;
    }

    /**
     * 将时长转换成00:00:00格式
     * @param integer $dur
     * @return string
     */
    public function formateTime($dur)
    {
        if ($dur < 0) {
            return '';
        } else {
            $hour   = intval($dur/3600);
            $dur    = $dur%3600;
            $minute = intval($dur/60);
            $second = $dur%60;
            if ($hour < 10) {
                $hour = "0".$hour;
            }
            if ($minute < 10) {
                $minute = "0".$minute;
            }
            if ($second < 10) {
                $second = "0".$second;
            }
            $formatDur = $hour.":".$minute.":".$second;

            return $formatDur;
        }
    }

    /**
     * 判断特殊菜单是否启用；
     * @param integer $menuId
     * @param integer $vccId
     * @return bool
     */
    public function isDisableMenu($menuId, $vccId)
    {
        if (!in_array($menuId, $this->keys)) {
            return true;
        }
        $ccod = $this->container->get("doctrine.orm.entity_manager")
            ->getRepository("IcsocSecurityBundle:CcCcodConfigs")->findOneBy(array('vccId'=>$vccId));
        if (empty($ccod)) {
            return true;
        }
        if (is_array($this->specialMenu[$menuId])) {
            $exhaledField = $this->specialMenu[$menuId][0];
            $inCommingField = $this->specialMenu[$menuId][1];

            return $ccod->$exhaledField() == 1 || $ccod->$inCommingField() == 1;
        }
        $field = $this->specialMenu[$menuId];

        return $ccod->$field() == 1 ? true : false;
    }

    /**
     * 设置缓存数据
     * @param string  $key
     * @param string  $data
     * @param integer $ttl
     */
    public function setCache($key, $data, $ttl = 86400)
    {
        $this->container->get('snc_redis.default')->set($key, $data);
        $this->container->get('snc_redis.default')->expire($key, $ttl);
        //$this->container->get('sonata.cache.predis')->set($key, $data, $ttl);
    }

    /**
     * 获取缓存数据
     * @param string $key
     * @return mixed
     */
    public function getCache($key)
    {
        //$cacheElement = $this->container->get('sonata.cache.predis')->get($key);
        $cacheElement = $this->container->get('snc_redis.default')->get($key);

        return json_decode($cacheElement, true);
    }

    /**
     * 根据设置获取黑名单类型；
     * @param integer $vccId
     * @return mixed
     */
    public function getBlacTypes($vccId)
    {
        $types = $this->container->getParameter("black_name_type");
        $types[0] = '全部';
        $config = $this->container->get("doctrine.orm.entity_manager")
            ->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->findOneBy(array('vccId'=>$vccId));
        if (empty($config)) {
            return $types;  //没有配置默认开启；
        }
        if (!$config->getIsEnableBlack()) {
            unset($types['2']); //禁用去掉呼出
        }
        if (!$config->getIsIncomingEnableBlack()) {
            unset($types['1']); //禁用去掉呼入;
        }
        ksort($types);

        return $types;
    }

    /**
     * @param string $html （需要过滤的字符串）
     * @return string
     */
    public function purifyHtml($html)
    {
        return $html;

        if (empty($html)) {
            return '';
        }
        $purifier = $this->container->get("icsoc_core.html.purifier.class")->get();

        return $purifier->purify($html);
    }


    /**
     * 添加更新记录表，以及通知分发服务有更新
     *
     * @param int    $id        更新的语音,ivr ID
     * @param int    $vccId     企业id
     * @param string $logAction 操作(create,update)
     * @param string $logType   操作类型(ivr,sound)
     * @return bool
     */
    public function addToChangelogAndSendNoticeToZmqServer($id, $vccId, $logAction = 'update', $logType = 'ivr')
    {
        if (empty($id)) {
            return false;
        }

        $conn = $this->container->get('doctrine.dbal.default_connection');

        $logger = $this->container->get('logger');
        //添加更新记录表
        $changelog = array(
            'vcc_id' => $vccId,
            'log_type' => $logType,
            'log_action' => $logAction,
            'table_id' => $id,
        );
        $ret = $conn->insert('cc_cti_change_logs', $changelog);
        $nid = $conn->lastInsertId();
        if ($ret <= 0) {
            $logger->critical(sprintf('Insert value %s to table cc_cti_change_logs failed.', json_encode($changelog)));

            return false;
        }

        //发送通知
        $zmqServer = $this->container->getParameter('cti_zmq_server');
        $zmqPort = $this->container->getParameter('cti_zmq_port');

        try {
            $context = new \ZMQContext();
            $requester = new \ZMQSocket($context, \ZMQ::SOCKET_REQ);
            $requester->connect("tcp://$zmqServer:$zmqPort");
            $msg = json_encode(array('nid' => intval($nid)));
            $requester->send($msg);
            $logger->info(sprintf('Send the request to the server %s:%s, the msg is %s.', $zmqServer, $zmqPort, $msg));

            $poll = new \ZMQPoll();
            $poll->add($requester, \ZMQ::POLL_IN);
            $readable = $writeable = array();
            $events = $poll->poll($readable, $writeable, 5000);
            $errors = $poll->getLastErrors();

            //存在错误
            if (count($errors) > 0) {
                foreach ($errors as $error) {
                    $logger->critical(sprintf("Error polling object, the error is %s", $error));

                    return false;
                }
            }

            //收到消息
            if ($events > 0) {
                foreach ($readable as $socket) {
                    if ($socket === $requester) {
                        $reply = $requester->recv();
                    }
                }
            } else {
                return false;
            }

            if (empty($reply)) {
                $logger->critical(sprintf('The reply of the request is empty, needs json.'));

                return false;
            }
            $replyArray = json_decode($reply, true);
            $jsonLastError = json_last_error();
            if ($jsonLastError != JSON_ERROR_NONE) {
                $logger->critical(sprintf('Json decode the reply %s failed, the error is %s.', $reply, $jsonLastError));

                return false;
            }

            $ret = isset($replyArray['ret']) ? $replyArray['ret'] : '-1';
            if ($ret === 0) {
                return true;
            } else {
                $logger->critical(sprintf('The ret of the reply %s is not 0, the reply is %s.', $ret, $reply));

                return false;
            }
        } catch (\ZMQPollException $e) {
            $logger->critical(sprintf('Poll failed: %s', $e->getMessage()));

            return false;
        }
    }

    /**
     * 如果存在从cc_cti_servers表中获取IP，不存在从cc_ccods表获取IP
     * @return mixed|string
     */
    public function newGetWinIp()
    {
        $winIp = '';
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $vccId = $user->getVccId();

        //查询关联字段的值
        $telid = $conn->fetchColumn(
            "SELECT telid
            FROM cc_ccods
            WHERE vcc_id = :vccid",
            array('vccid'=>$vccId)
        );

        //查询用户IP是否存在cc_cti_servers表中
        if ($telid) {
            $winIp = $conn->fetchColumn(
                "SELECT tel_addr
                FROM cc_cti_servers
                WHERE telid = ? ",
                array($telid)
            );
        }
        $winIp = empty($winIp) ? $user->getWinIp() : $winIp;

        return $winIp;
    }

    public function getTtsSound($content)
    {
        $ttsApi = $this->container->getParameter('tts_api');
        $ttsRootPath = $this->container->getParameter('tts_root_path');
        if (function_exists('mb_convert_encoding')) {
            $text = mb_convert_encoding($content, 'GBK', 'UTF-8');
        } else {
            $text = iconv('UTF-8', 'GBK//IGNORE', $content);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $ttsApi);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, sprintf('text=%s', $text));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $response = curl_exec($ch);
        curl_close($ch);
        $logger = $this->container->get('logger');
        if ($response === false) {
            $logger->error(sprintf(
                '发送【%s】到【%s】失败',
                $content,
                $ttsApi
            ));

            return array('error'=>true);
        }

        $responseArray = json_decode($response, true);
        if (json_last_error() != JSON_ERROR_NONE) {
            $logger->error(sprintf(
                'json解析字符串【%s】失败，错误为【%s】',
                $response,
                json_last_error()
            ));

            return array('error'=>true);
        }

        $ret = isset($responseArray['ret']) ? $responseArray['ret'] : -1;
        $msg = empty($responseArray['msg']) ? '' : $responseArray['msg'];
        if ($ret === 0) {
            $logger->info(sprintf('tts合成文本【%s】成功，结果为【%s】', $content, $msg));
            $path= str_ireplace('.wav', '', $ttsRootPath.$msg);

            return array('error'=>false, 'path'=>$path);
        } else {
            $logger->error(sprintf('tts合成文本【%s】失败，错误为【%s:%s】', $text, $ret, $msg));

            return array('error'=>true);
        }
    }

    /**
     * 坐席登录只能查看最近两个月的数据（百度定制）
     *
     * @param $startTime  //开始时间
     * @param $endTime  //结束时间
     * @param $dateType  //时间类型(日期，时间戳)
     * @return array
     */
    public function rolesCanSearchAllReportDatas($startTime, $endTime, $dateType)
    {
        //百度的企业id
        $baiduVccId = 2000004;
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $vccId = $user->getVccId();
        $loginType = $user->getLoginType();
        if ($vccId == $baiduVccId) {
            $roleId = 516;
            $isAdmin = true;
            if ($loginType == 2) {
                //获取坐席角色
                $roleId = $user->getUserRole();
                $isAdmin = false;
            }

            $specialRoles = $this->roles;
            $newStartTime = '';
            $newEndTime = $endTime;

            //如果该角色不在配置的特殊角色中，那么只能查看近两个月内的报表数据
            if (!in_array($roleId, $specialRoles) && $isAdmin == false) {
                if ($dateType == 'date') {
                    if (empty($startTime) || $startTime == false) {
                        $startTime = date('Y-m-d').' 00:00:00';
                    }
                    if (empty($endTime) || $endTime == false) {
                        $endTime = date('Y-m-d').' 23:59:59';
                    }

                    //获取当月的最后一天
                    $days = date("t");
                    $currentLastDate = date('Y-m-'.$days, strtotime(date("Y-m-d"))).' 23:59:59';
                    $newEndTime = $endTime;
                    if ($endTime > $currentLastDate) {
                        $newEndTime = $currentLastDate;
                    }
                    if (date("n") == 1) {
                        $tmpMonth = 12;
                        $tmpYear = date ("Y") - 1;
                        $newStartTime = $tmpYear.'-'.$tmpMonth.'-01 00:00:00';
                    } else {
                        $tmpMonth = date("n") - 1;
                        $tmpYear = date("Y");
                        if (strlen($tmpMonth) == 1) {
                            $tmpMonth = '0'.$tmpMonth;
                        }
                        $newStartTime = $tmpYear . '-' . $tmpMonth . '-01 00:00:00';
                    }
                    if ($startTime > $newStartTime && $startTime < $currentLastDate) {
                        $newStartTime = $startTime;
                    }
                }

                if ($dateType == 'timestamp') {
                    if (empty($startTime) || $startTime == false) {
                        $startTime = time();
                    }
                    if (empty($endTime) || $endTime == false) {
                        $endTime = time();
                    }

                    $currentTime = time();
                    $newEndTime = $endTime;
                    if ($endTime > $currentTime) {
                        $newEndTime = $currentTime;
                    }
                    if (date("n") == 1) {
                        $tmpMonth = 12;
                        $tmpYear = date ("Y") - 1;
                        $newStartTime = strtotime("$tmpYear".'-'.$tmpMonth.'-01');
                    }else {
                        $tmpMonth = date("n") - 1;
                        $tmpYear = date("Y");
                        if (strlen($tmpMonth) == 1) {
                            $tmpMonth = '0'.$tmpMonth;
                        }
                        $newStartTime = strtotime("$tmpYear" . '-' . $tmpMonth . '-01');
                    }
                    if ($startTime > $newStartTime && $startTime < $currentTime) {
                        $newStartTime = $startTime;
                    }
                    if ($startTime > $currentTime) {
                        return 'no';
                    }
                }

                return array('startTime' => $newStartTime, 'endTime' => $newEndTime);
            } else {
                return array('startTime' => $startTime, 'endTime' => $endTime);
            }
        } else {
            return array('startTime' => $startTime, 'endTime' => $endTime);
        }

    }

    public function getIsAdmin()
    {
        //百度的企业id
        $baiduVccId = 2000004;
        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $vccId = $user->getVccId();
        if ($vccId == $baiduVccId) {
            $loginType = $user->getLoginType();
            $roleId = 516;
            $isAdmin = true;
            $isSpecial = 2;
            if ($loginType == 2) {
                //获取坐席角色
                $roleId = $user->getUserRole();
                $isAdmin = false;
            }

            //百度特殊情况
            if ($isAdmin == false && !in_array($roleId, $this->roles)) {
                $isSpecial = 1;
            }
        } else {
            $isSpecial = 2;
        }

        return $isSpecial;
    }

    /**
     * 查看是否拥有某种权限
     * @param $menuUrl
     * @return bool
     */
    public function getWhetherHaveAuthority($menuUrl)
    {
        $actionList = $this->container->get("security.token_storage")->getToken()->getUser()->getActionList();
        $actions = explode(',', $actionList);
        $haveing = ($actionList == 'all'  || in_array($menuUrl, $actions))
            ? true : false;

        return $haveing;
    }


    /**
     * 用136*****的方法隐藏客户号码
     * @param $phone
     * @param $authority
     * @return string
     */
    public function concealCusPhone($phone, $authority)
    {
        if (empty($phone)) {
            return '';
        }
        if ($authority) {
            return $phone;
        }
        $strPhone = substr($phone, 0, 3);
        $strPhone .= str_repeat('*', 4);
        $strPhone .= empty(substr($phone, 7)) ? '' : substr($phone, 7);

        return $strPhone;
    }
}
